"""
DAQ数据处理应用程序主入口点
连接UI和业务逻辑，使用信号与槽机制进行解耦
"""

import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QObject, pyqtSlot

from ui.main_window import MainWindow
from core.data_processor import DataProcessor


class Application(QObject):
    """应用程序控制器，负责连接UI和业务逻辑"""
    
    def __init__(self):
        super().__init__()
        self.data_processor = DataProcessor()
        self.main_window = MainWindow()
        
        # 连接信号与槽
        self.connect_signals()
        
    def connect_signals(self):
        """连接UI信号与业务逻辑槽"""
        # 文件加载完成信号
        self.main_window.files_loaded.connect(self.on_files_loaded)
        
        # 绘图请求信号
        self.main_window.plot_requested.connect(self.on_plot_requested)
        
        # 预览请求信号
        self.main_window.preview_requested.connect(self.on_preview_requested)
    
    @pyqtSlot(list)
    def on_files_loaded(self, filepaths):
        """
        处理文件加载完成事件
        
        Args:
            filepaths: 文件路径列表
        """
        try:
            result = self.data_processor.process_files_loaded(filepaths)
            if result:
                # 更新UI中的参数值
                if 'fs_mhz' in result:
                    self.main_window.set_fs_value(result['fs_mhz'])
                if 't_max_us' in result:
                    self.main_window.set_time_end_value(result['t_max_us'])
                
                # 显示参数加载成功消息
                import os
                filename = os.path.basename(filepaths[0])
                self.main_window.show_info_message(
                    "参数加载完成", 
                    f"从 {filename} 加载的参数已应用"
                )
        except Exception as e:
            self.main_window.show_error_message(
                "文件加载错误", 
                f"处理文件时出错: {str(e)}"
            )
    
    @pyqtSlot(dict)
    def on_plot_requested(self, parameters):
        """
        处理绘图请求
        
        Args:
            parameters: 绘图参数字典
        """
        try:
            result = self.data_processor.process_plot_request(parameters)
            
            if result['success']:
                # 如果是保存模式且有新的文件路径，更新UI
                if 'new_filepaths' in result:
                    self.main_window.filepaths = result['new_filepaths']
                    self.main_window.update_filename_display()
                
                # 显示成功消息
                self.main_window.show_info_message("操作完成", result['message'])
            else:
                # 显示错误消息
                self.main_window.show_error_message("操作失败", result['message'])
                
        except Exception as e:
            self.main_window.show_error_message(
                "绘图错误", 
                f"绘图过程中出现意外错误: {str(e)}"
            )
    
    @pyqtSlot()
    def on_preview_requested(self):
        """处理预览请求"""
        try:
            preview_text = self.data_processor.process_preview_request(
                self.main_window.filepaths
            )
            self.main_window.show_preview_info(preview_text)
        except Exception as e:
            self.main_window.show_error_message(
                "预览错误", 
                f"无法预览文件: {str(e)}"
            )
    
    def run(self):
        """运行应用程序"""
        self.main_window.show()
        return QApplication.instance().exec_()


def main():
    """主函数"""
    app = QApplication(sys.argv)
    
    # 创建应用程序控制器
    application = Application()
    
    # 运行应用程序
    exit_code = application.run()
    
    sys.exit(exit_code)


if __name__ == '__main__':
    main() 